﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace DotNet.Helper
{
    /// <summary>
    /// Xml帮助类
    /// </summary>
    public class XmlHelper
    {
        #region 反序列化
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static object Deserialize(Type type, string path)
        {
            object obj = null;
            using (StreamReader reader = new StreamReader(path,Encoding.UTF8))
            {
                try
                {
                    XmlSerializer serializer = new XmlSerializer(type);
                    obj = serializer.Deserialize(reader);
                }
                catch (Exception)
                {
                    throw;
                }
            }
            return obj;
        }
        #endregion

        #region 序列化
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <param name="path">保存路径</param>
        public static void Serializer(Type type, object obj, string path)
        {
            using (StreamWriter writer = new StreamWriter(path, false, Encoding.UTF8, 1000))
            {
                try
                {
                    XmlSerializer serializer = new XmlSerializer(type);
                    serializer.Serialize(writer, obj);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        #endregion

    }
}
